package campus.aiit.ssl.controller;

import campus.aiit.ssl.service.IndexService;
import com.iflytek.uaac.client.rest.context.UaacServiceContext;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;
import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;


/**
 * 登陆认证的处理、注销，etc
 *
 * @author ihaokun
 * @date 2019/9/27 11:09
 */
@Api(description = "登录/登出")
@Slf4j
@Controller
public class IndexController {
  @Value("${backEnd.index}") private String backIndex;
  @Value("${frontEnd.index}") private String adminUrl;
  @Value("${frontEnd.generalAdmin}") private String generalAdminUrl;
  @Value("${frontEnd.user}") private String userUrl;
  @Resource private IndexService indexService;

  // "登陆接口，携带 认证 通过后的cookie重定向到首页"
  /*@GetMapping
  public String login(HttpServletRequest request) {
    // 携带SSO认证得到的Cookie，重定向到首页
    return "redirect:" + frontIndex + "?" + request.getHeader("Cookie");
  }*/
  @GetMapping
  public void login(HttpServletRequest req, HttpServletResponse resp) throws IOException {
    String[] url = {adminUrl,generalAdminUrl,userUrl};
    indexService.login(req, resp,url);
  }

  @ApiOperation("登出接口")
  @GetMapping("logout")
  public String logout(HttpServletRequest request, HttpServletResponse response)
      throws UnsupportedEncodingException {
    indexService.logout(request, response);
    String casUrl = backIndex;
    return "redirect:"
        + UaacServiceContext.getUaacConstant().getCasContext()
        + UaacServiceContext.getUaacConstant().getCasContextLogout()
        + "?service="
        + URLEncoder.encode(casUrl, "utf-8");
  }

  // @ApiOperation("用户基本信息接口")
//  @GetMapping("/userInfo")
//  public Map<String , Object> getUserInfo(
//      HttpServletRequest request, HttpServletResponse response) {
//    // 测试前后端分离，每次请求session是否相同
//    log.info("测试前后端分离，每次请求session是否相同");
//    log.info(request.getSession().getId());
//    Map<String , Object> map = new HashMap<>();
//    com.iflytek.uaac.common.domain.User user = indexService.userInfo(request.getSession());
//    map.put("userId",user.getLoginName());
//    map.put("userName",user.getName());
//    int roleId = userService.userWithBlocks(user.getLoginName()).getRoleId();
//    map.put("roleId",roleId);
//    System.out.println(map);
//    return map;
//  }
}